package com.cicadamob.contact.api.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Environment;
import android.os.Handler;
import android.widget.Toast;

import com.cicadamob.contact.api.Utils.ContactConfig;
import com.cicadamob.contact.api.Utils.StringUtil;
import com.cicadamob.contact.api.Utils.Endecryption.EndecryptionUtil;

/**
 * 通讯录全量更新（下载通讯录）
 * @author Administrator
 *
 */
public class DownLoadContactAsynTask implements Runnable {
	protected UpdateState updateState = null;
	protected Context context;
//	private Handler myHandler;
//	private int what;
	public static int DOWNLOAD_STATUS=0;
	/**正在下载*/
	public static final int DOWNLOAD_LOADING=1;
	/**下载失败*/
	public static final int DOWNLOAD_FAILE=2;
	/**下载成功*/
	public static final int DOWNLOAD_SUCCEED=3;
	/**
	 * 通讯录更新
	 */
	public static final String CONTACT_UPDATE_ACTION="com.gmccgz.contact.update";
	/**
	 * 通讯录更新失败
	 */
	public static final String CONTACT_UPDATE_ACTION_FAILE="com.gmccgz.contact.update.faile";
	
	public DownLoadContactAsynTask(Context context) {
		this.context=context;
		updateState = new UpdateState();
		
	}
	
	private  boolean loadingContactDbToRam(Context context){
		//读取整个文件到内存数据库中
		try
		{
			FileOutputStream fos = context.openFileOutput( ContactDbHelper.DBFILE, 0 );
			FileInputStream fis = new FileInputStream( FilePath.DOWNLOAD_PATH 
					+ ContactDbHelper.DBFILE );
			byte[] buffer = new byte[1024 * 4];
			int len = 0;
			while ( ( len = fis.read( buffer ) ) != -1 )
			{
				fos.write( buffer, 0, len );
			}
			fis.close();
			fos.close();
			File file = new File(FilePath.DOWNLOAD_PATH 
					+ ContactDbHelper.DBFILE);
			//删除sd卡的临时文件
			if(file.exists())
				file.delete();
			file = null;
			fis = null;
			fos = null;
		} catch ( IOException e ){
			e.printStackTrace();
			return false;
		}
		return true;
	}



	@Override
	public void run() {
		// TODO Auto-generated method stub
       DOWNLOAD_STATUS=DOWNLOAD_LOADING;
		
		String encdata =ContactConfig.getMobile(context)+";" + ContactConfig.getIMSI(context) + ";"
				+ ContactConfig.getIMEI(context) + ";" + StringUtil.getRandomStr(7) + ";"
				+ StringUtil.getStrDate(new Date(), "yyyy-MM-dd hh:mm:ss");
		String des = EndecryptionUtil.encode3DesAndBase64(encdata,
				ContactHttpClient.KEY);
		String dd = StringUtil.encode(des);
//		String fileName=Environment.getExternalStorageDirectory().getAbsolutePath()+"/ManagerAssistant/download/";
		String mobile=ContactConfig.getMobile(context);
		String imsi=ContactConfig.getIMSI(context);
		String imei=ContactConfig.getIMEI(context);
		String version="0";
		String authentication=dd;
		String Connection="close";
		Map<String, String> requestParam=new HashMap<String, String>();
		requestParam.put("mobile", mobile);
		requestParam.put("imsi", imsi);
		requestParam.put("imei", imei);
		requestParam.put("version", version);
		requestParam.put("authentication", authentication);
		requestParam.put("Connection", Connection);
		
		int status = ContactHttpClient.downloadFile(ServerUrl.COMPANY_ZIP_URL+"?token="+ContactConfig.getToken(context) , requestParam, DownloadUtils.DOWNLOAD_PATH, ContactDbHelper.DBFILE);
		
		try {
			Thread.sleep(10000);
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		if(status == ContactHttpClient.CODE_OK) {
			//拷贝文件至内存中，并删除SD卡上的文件。
			try {
				String path = DownloadUtils.DOWNLOAD_PATH + ContactDbHelper.DBFILE;
				boolean canOpen = ContactDbHelper.canOpen(path);//打开数据库
				if(canOpen) {
					boolean suc = loadingContactDbToRam( context );//将数据库拷贝到内存，并删除下载在sd卡上的文件
					ContactDbHelper.reloadDataBase();
					if(suc){
					//生成同事组织路径
					ContactDbHelper.getInstance().createComPanyTreePath();
					}
					if(downloadClientDB()){
						//生成客户组织路径
						ContactDbHelper.getInstance().createClientTreePath();
					}
					
					DOWNLOAD_STATUS=DOWNLOAD_SUCCEED;
					
//					Toast.makeText( context, "通讯录更新成功", Toast.LENGTH_LONG ).show();
					
					Intent intent=new Intent(CONTACT_UPDATE_ACTION);
					context.sendBroadcast(intent);
				}
			} catch ( Exception e ) {
				e.printStackTrace();
				DOWNLOAD_STATUS=DOWNLOAD_FAILE;
			}
			showErrorTip();
		} else if(status == ContactHttpClient.CODE_CONFLICT) {
			DOWNLOAD_STATUS=DOWNLOAD_FAILE;
			updateState.state = UpdateState.CONTACT_CONFLICT;
			showErrorTip();
		} else  {
			DOWNLOAD_STATUS=DOWNLOAD_FAILE;
			if(status == ContactHttpClient.CODE_UNAUTHORIZED)
				updateState.state = UpdateState.UNPERMISSION_EXCEPTION;
			else if (status == ContactHttpClient.CODE_NET_ERROR)
				updateState.state = UpdateState.NET_EXCEPTION;
//			else if(StringUtil.isEmpty( PrefConfig.MOBILE ))
//				updateState.state = UpdateState.MOBILE_NOT_EXIST;
//			else if(StringUtil.isEmpty( PrefConfig.IMSI ))
//				updateState.state = UpdateState.IMSI_NOT_EXIST;
			else if(status == ContactHttpClient.CODE_SERVERERROR)
				updateState.state = UpdateState.SERVER_EXCEPTION;
			else if(status == ContactHttpClient.TAKEDBFILEERROR)
				updateState.state = UpdateState.SERVER_EXCEPTION;
			else if (status == UpdateState.TOKEN_NULL) 
				updateState.state = UpdateState.TOKEN_NULL;
			else if (status == UpdateState.TOKEN_OUT_DATE) 
				updateState.state = UpdateState.TOKEN_OUT_DATE;
			else if (status == UpdateState.USER_NULL) 
				updateState.state = UpdateState.USER_NULL;
			else if (status == UpdateState.TOKEN_REQUEST_ERROR) 
				updateState.state = UpdateState.TOKEN_REQUEST_ERROR;
			else if (status == UpdateState.OTHER_ERROR) 
				updateState.state = UpdateState.OTHER_ERROR;
			showErrorTip();
		}
	}
	
	private void showErrorTip(){
		String tip = updateState.getTip();
		if ( tip != null ) {
			DOWNLOAD_STATUS=DOWNLOAD_FAILE;
//			Toast.makeText( context, tip, Toast.LENGTH_LONG ).show();
			context.deleteFile(ContactDbHelper.DBFILE);
			Intent intent=new Intent(CONTACT_UPDATE_ACTION);
			context.sendBroadcast(intent);
		}
	}
	
	
	/**加载客户数据文件
	 * @return
	 */
	private boolean downloadClientDB() {
		String encdata =ContactConfig.getMobile(context)+";" + ContactConfig.getIMSI(context) + ";"
				+ ContactConfig.getIMEI(context) + ";" + StringUtil.getRandomStr(7) + ";"
				+ StringUtil.getStrDate(new Date(), "yyyy-MM-dd hh:mm:ss");
		String des = EndecryptionUtil.encode3DesAndBase64(encdata,
				ContactHttpClient.KEY);
		String dd = StringUtil.encode(des);
		
		String mobile=ContactConfig.getMobile(context);
		String imsi=ContactConfig.getIMSI(context);
		String imei=ContactConfig.getIMEI(context);
		String version="0";
		String authentication=dd;
		String Connection="close";
		Map<String, String> requestParam=new HashMap<String, String>();
		requestParam.put("mobile", mobile);
		requestParam.put("imsi", imsi);
		requestParam.put("imei", imei);
		requestParam.put("version", version);
		requestParam.put("authentication", authentication);
		requestParam.put("Connection", Connection);
		
		String url = StringUtil.getBuffer().append(ServerUrl.CLIENT_DATA_URL).append("?mobile=" + mobile).toString();
		
		String fileName = mobile + "_clientdata.txt";
		//下载需要更新文件
		int status=ContactHttpClient.downloadFile(url , requestParam, DownloadUtils.DOWNLOAD_PATH, fileName);
		if(status == 200) {
			try {
				parseJsonFile(fileName);
			} catch (ServerException e) {
				/**2013-7-19下午3:35:51 请别忘记对异常进行处理 Administrator ServerException*/
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}
	
	/**
	 * 解析下载下来的需要更新的json文件
	 * @param filename
	 * @return
	 * @throws ServerException
	 */
	private void parseJsonFile(String filename)throws ServerException {
		File file = new File(DownloadUtils.DOWNLOAD_PATH + filename);
		BufferedReader br = null;
		FileInputStream fis = null;
		List<String> sqlList=new ArrayList<String>();
		try {
			fis = new FileInputStream(file);
			br = new BufferedReader(new InputStreamReader(fis));
			String sqlValue = null;
			//miaozz add 因为客户表可添加多个公司节点为-1，故在上层再添加一个节点为-2
//			if(Const.CRMASSISTANT == ServerUrl.ProjectNO) {
//				ContactDbHelper.getInstance().insert2ClientTree();
//			}
			
			while((sqlValue = br.readLine()) != null) {
				sqlList.add(sqlValue);
				//ContactDbHelper.getInstance().executeSQL(sqlValue);
			}
			ContactDbHelper.getInstance().executesql(sqlList);
		} catch (FileNotFoundException e) {
			/**2013-7-19下午6:22:16
			     请别忘记对异常进行处理 Administrator
			    FileNotFoundException
			*/
			e.printStackTrace();
		} catch (IOException e) {
			/**2013-7-19下午6:24:48
			     请别忘记对异常进行处理 Administrator
			    IOException
			*/
			e.printStackTrace();
		}catch(Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if(br != null) {
					br.close();
				}
				
				if(fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				/**2013-7-19下午6:31:54
				     请别忘记对异常进行处理 Administrator
				    IOException
				*/
				e.printStackTrace();
			}
			if(file.exists()) file.delete();
		}
	}
	
}
